// pages/login/index.js
import { checkPhone, checkEmail } from '../../utils/util'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import api from '../../utils/api'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    success:true,
    btntext:'微信授权登录',
    authflag:true,
    authstyle:'',
    gourl : '',
    logincode:'',
    authres:''
  },

  async send() {
    let data={}
    data['flag'] = 'get_auth'
    data['code'] = this.data.logincode
    data['data'] = JSON.stringify(this.data.authres)
    //console.log(JSON.stringify(data))
//return
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      console.log(result)
      for(let p in result)
      app.globalData.userInfo[p] = result[p]
      app.globalData.userInfo.name = result.nickName
      app.globalData.userInfo.avatar = result.avatarUrl

      wx.reLaunch({
        url: this.data.gourl
      })
    }else {
      Toast(message)
    }

  },

  async auth(){
      let _this = this
    if(!this.data.authflag){
      wx.login({
				success: function (res) {
          console.log(res.code)
          _this.setData({logincode:res.code})
        }
      })
      wx.getUserProfile({
        desc: '用于完善会员资料', 
        success: (res) => {
          console.log(JSON.stringify(res))
          _this.setData({authres:res})
          _this.send()
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
    let url = options.url||'/pages/my/index';
    if( url.substr(0,6)!='/pages' ) url = decodeURIComponent(url)
    this.setData({ gourl:url })

    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userInfo']) {
          _this.setData({authflag:false,btntext:'微信授权登录',authstyle:'authbtn'})
        }else{
          if( !app.globalData.userInfo.name ){
            _this.setData({authflag:false,btntext:'微信授权登录',authstyle:'authbtn'})
          }else{
            _this.setData({authflag:true,btntext:'微信已授权',authstyle:''})
          }
        }
      },
      fail: error => {
        console.log(error);
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})